package com.qwt.server.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qwt.server.advice.FException;
import com.qwt.server.bean.FileMetaBo;
import com.qwt.server.bean.FileResTo;
import com.qwt.server.response.R;
import com.qwt.server.service.FileMetaService;
import com.qwt.server.utils.FileUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.util.Objects;

/**
 * @author 时光
 * @date 2021/12/09 18:2646
 */
@Slf4j
@RestController
@RequestMapping("/file-server")
public class FileController {
    /**
     * 端口
     */
    @Value("${server.port}")
    public String port;

    /**
     * 根路径
     */
    @Value("${server.servlet.context-path}")
    public String contextPath;

    @Autowired
    FileMetaService fileMetaService;

    @Autowired
    private ObjectMapper mapper;

    @SneakyThrows
    @PostMapping("/upload")
    @Transactional(rollbackFor = Exception.class)
    public R upload(MultipartFile multipartFile){
        FileResTo fileResTo = FileUtil.uploadFile(multipartFile);
        log.info("文件-上传 ==> 上传日志:{}",mapper.writeValueAsString(fileResTo));
        if (Objects.isNull(fileResTo.getIfTransferToSuccess()) || !fileResTo.getIfTransferToSuccess()){
            return R.error("操作失败");
        }
        FileMetaBo fileMetaBo = fileResTo.getFileMetaBo();
        fileMetaBo.setUrl("http://"+ InetAddress.getLocalHost().getHostAddress() +":"+port+contextPath+(fileMetaBo.getSavePath().substring(fileMetaBo.getSavePath().indexOf("static/")+6).replaceAll("\\\\","/")));
        boolean res = fileMetaService.saveOrUpdate(fileMetaBo);
        return R.ok().put("isSave",res).put("uuid",fileMetaBo.getUuid());
    }

    @SneakyThrows
    @GetMapping("/download/{uuid}")
    public void download(@PathVariable String uuid, HttpServletResponse response){
        if (Objects.isNull(uuid)){
            throw  FException.of("缺少必要参数",501);
        }
        FileMetaBo fileMetaBo = fileMetaService.getById(uuid);
        log.info("文件-下载 ==> 记录查询结果:{}",mapper.writeValueAsString(fileMetaBo));
        FileUtil.downloadFile(response, fileMetaBo);
    }


    @GetMapping("/info")
    public R delete(@RequestBody FileMetaBo fileMetaBo){
        if (Objects.isNull(fileMetaBo) || Objects.isNull(fileMetaBo.getUuid())){
            return R.error("缺少必要字段[uuid]");
        }
        FileMetaBo queryOne = fileMetaService.getById(fileMetaBo);
        return R.ok().put("meta",queryOne);
    }
}
